import Dialog from 'tdesign-miniprogram/dialog/index';
import Toast from 'tdesign-miniprogram/toast/index';
// import { fetchCartGroupData } from '../../services/cart/cart';
import {
  getGoods
} from '../../../services/good/index';
let total = 0;
Page({
  data: {
    loading: false,
    cartGroupData: [],
    isAllSelected: false,
    totalAmount: 0,
    totalGoodsNum: 0,
    selectedGoodsCount: 0,
    pArr: [],
  },

  // 调用自定义tabbar的init函数，使页面与tabbar激活状态保持一致
  async onShow() {
    this.onRest();
    await this.init();
    this.setData({
      loading: true,
    });
  },

  onLoad() {
    // this.refreshData();
  },
  onRest() {
    total = 0;
    this.setData({
      cartGroupData: [],
      totalAmount: 0,
      isAllSelected: false,
      totalGoodsNum: 0,
      selectedGoodsCount: 0,
    });
  },
  init() {
    const data = wx.getStorageSync('carList') || [];
    if (data && data.length > 0) {
      for (const item of data) {
        this.getDetail(item.key, item.value);
      }
    }
  },
  getDetail(spuId, num) {
    getGoods({
      kid: spuId,
    }).then((res) => {
      const details = res.data;
      details.price = details.price > 0 ? this.priceInt(details.price).join('.') : 0;
      if (details.picSmall) {
        details.images = details.picSmall.split();
      }
      this.data.cartGroupData.push({
        ...details,
        num,
      });
      this.setData({
        cartGroupData: this.data.cartGroupData,
      });
    });
  },
  remove(e) {
    const carList = wx.getStorageSync('carList') || [];
    const {
      id
    } = e.currentTarget.dataset;
    const index = this.data.cartGroupData.findIndex((item) => item.kid === id);
    const cindex = carList.findIndex((item) => item.key === id);
    carList.splice(cindex, 1);
    this.data.cartGroupData.splice(index, 1);
    this.setData({
      cartGroupData: this.data.cartGroupData,
    });
    wx.setStorage({
      key: 'carList',
      data: carList,
    });
  },
  // 计算选中价格总数
  totalAmountWatch(item) {
    if (item.isSelected) {
      total += Number(item.price) * item.num;
    } else {
      total -= Number(item.price) * item.num;
    }
    const selscted = this.data.cartGroupData.every((item) => item.isSelected === true);
    this.setData({
      totalAmount: total,
      isAllSelected: selscted,
    });
  },
  onGoodsSelect(e) {
    const that = this;
    const {
      goods: {
        kid
      },
      isSelected,
    } = e.detail;
    const index = that.data.cartGroupData.findIndex((item) => item.kid === kid);
    that.data.cartGroupData[index].isSelected = isSelected;
    that.setData({
      cartGroupData: that.data.cartGroupData,
    });

    setTimeout(() => {
      const selector = that.data.cartGroupData.every((item) => item.isSelected === true);
      if (selector) {
        that.setData({
          isAllSelected: isSelected,
        });
      }
      const item = that.data.cartGroupData[index];

      if (item.isSelected) {
        that.data.selectedGoodsCount++;
      } else {
        that.data.selectedGoodsCount--;
      }
      that.setData({
        selectedGoodsCount: that.data.selectedGoodsCount,
      });
      that.totalAmountWatch(item);
    }, 200);
    // const { currentGoods } = this.findGoods(spuId, skuId);
    Toast({
      context: this,
      selector: '#t-toast',
      message: `${isSelected ? '选择商品' : '取消'}`,
      icon: '',
    });
    // this.selectGoodsService({
    //   spuId,
    //   skuId,
    //   isSelected,
    // }).then(() => this.refreshData());
  },

  onStoreSelect(e) {
    let AllTotal = 0;
    const {
      isSelected
    } = e.detail;
    for (const item of this.data.cartGroupData) {
      item.isSelected = isSelected;
    }
    this.setData({
      cartGroupData: this.data.cartGroupData,
      isAllSelected: isSelected,
    });
    for (const item of this.data.cartGroupData) {
      AllTotal += item.price;
    }
    if (!isSelected) {
      total = 0;
      this.setData({
        totalAmount: 0,
        selectedGoodsCount: 0,
      });
    } else {
      this.setData({
        totalAmount: AllTotal,
        selectedGoodsCount: this.data.cartGroupData.length,
      });
    }
  },
  onGoodsDelete(e) {
    const {
      goods: {
        kid
      },
    } = e.detail;
    Dialog.confirm({
        content: '确认删除该商品吗?',
        confirmBtn: '确定',
        cancelBtn: '取消',
      })
      .then(() => {
        const carList = wx.getStorageSync('carList') || [];
        const index = this.data.cartGroupData.findIndex((item) => item.kid === kid);
        const cindex = carList.findIndex((item) => item.key === kid);
        if (cindex > -1) {
          this.data.cartGroupData[index].isSelected = false;
          this.totalAmountWatch(this.data.cartGroupData[index]);
        }
        carList.splice(cindex, 1);
        this.data.cartGroupData.splice(index, 1);
        this.setData({
          cartGroupData: this.data.cartGroupData,
        });
        const selscted = this.data.cartGroupData.every((item) => item.isSelected === true);
        this.setData({
          isAllSelected: selscted,
        });
        wx.setStorage({
          key: 'carList',
          data: carList,
        });
      })
      .catch(() => console.log('点击了取消'))
      .finally(() => Dialog.close());
  },

  onSelectAll(event) {
    const {
      isAllSelected
    } = event?.detail;
    let AllTotal = 0;
    for (const item of this.data.cartGroupData) {
      item.isSelected = isAllSelected;
    }
    this.setData({
      cartGroupData: this.data.cartGroupData,
      isAllSelected: isAllSelected,
    });
    for (const item of this.data.cartGroupData) {
      AllTotal += item.price * item.num;
    }
    if (!isAllSelected) {
      total = 0;
      this.setData({
        totalAmount: 0,
        selectedGoodsCount: 0,
      });
    } else {
      this.setData({
        totalAmount: AllTotal.toFixed(2),
        selectedGoodsCount: this.data.cartGroupData.length,
      });
    }
    // Toast({
    //   context: this,
    //   selector: '#t-toast',
    //   message: `${isAllSelected ? '取消' : '点击'}了全选按钮`,
    // });
    // 调用接口改变全选
  },

  //去结算
  onToSettle() {
    const goodsRequestList = [];
    this.data.cartGroupData.forEach((promotion) => {
      if (promotion.isSelected) {
        goodsRequestList.push({
          key: promotion.kid,
          value: Number(promotion.num),
        });
      }
    });
    wx.setStorageSync('order.goodsRequestList', JSON.stringify(goodsRequestList));
    wx.navigateTo({
      url: '/pages/order/order-confirm/index?type=cart',
    });
  },

  priceInt(price) {
    const pArr = [];
    price = Math.round(price * 10 ** 8) / 10 ** 8; // 恢复精度丢失
    price = Math.ceil(price); // 向上取整
    pArr[0] = price >= 100 ? `${price}`.slice(0, -2) : '0';
    pArr[1] = `${price + 100}`.slice(-2);
    this.setData({
      pArr,
    });
    return pArr;
  },
  onGotoHome() {
    wx.switchTab({
      url: '/pages/home/home',
    });
  },
});